package com.hungdev.trangxanh;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Calendar;

import com.android.internal.telephony.ITelephony;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class BlockCallService extends Service {

	private boolean isRunning;
	private int fromHour;
	private int fromMinute;
	private int toHour;
	private int toMinute;
	private static boolean STARTED;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		// super.onCreate();
		Log.e("create service", "create service");
		Toast.makeText(this, "Block call enable", Toast.LENGTH_SHORT).show();
		isRunning = true;

		// tao notifications :v
		/*NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				this).setSmallIcon(R.drawable.ic_launcher)
				.setContentTitle("Block call is running :3")
				.setContentText("Có cuộc gọi đến là bố tắt ngay :v");
		NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		//mId allow you to update the notification later on.
		mNotificationManager.notify(1, mBuilder.build());*/
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		
		//http://diendan.congdongcviet.com/threads/t199967::service-bi-tat-khi-kill-app-thi-xu-ly-the-nao.cpp
		if (STARTED){
			return START_STICKY;
		}
		
		if (Build.VERSION.SDK_INT < 20){
			startForeground(6677028, new Notification());
			this.onStart(intent, startId);
		}
		STARTED = true;
		

		// lay du lieu duoc gui tu activity
		if (intent != null) {
			fromHour = intent.getIntExtra("fromHour", -1);
			fromMinute = intent.getIntExtra("fromMinute", -1);
			toHour = intent.getIntExtra("toHour", -1);
			toMinute = intent.getIntExtra("toMinute", -1);
		}

		// thuc hien chan cuoc goi

		final TelephonyManager telMgr = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);

		PhoneStateListener phoneStateListener = new PhoneStateListener() {
			public void onCallStateChanged(int state, String incomingNumber) {
				// telMgrOutput.setText(getTelephonyOverview(telMgr));
				String phoneState = getTelephonyOverview(telMgr);

				try {
					Class c = Class.forName(telMgr.getClass().getName());
					Method method = c.getDeclaredMethod("getITelephony");
					method.setAccessible(true);
					ITelephony telephonyService = (ITelephony) method
							.invoke(telMgr);

					if (phoneState.equals("RINGING")) {
						Calendar cal = Calendar.getInstance();
						int h = cal.get(Calendar.HOUR_OF_DAY);
						int m = cal.get(Calendar.MINUTE);
						if (isRunning == false) {
							Toast.makeText(getApplicationContext(),
									"isRunning == false @@", Toast.LENGTH_SHORT)
									.show();
						}
						if (isRunning) {
							Toast.makeText(getApplicationContext(),
									"isRunning == true", Toast.LENGTH_SHORT)
									.show();
							if (fromHour == -1) {
								telephonyService.endCall();
							} else {
								if (fromHour > toHour) {
									if (h >= fromHour && m >= fromMinute) {
										telephonyService.endCall();
									}
									if (h < toHour) {
										telephonyService.endCall();
									} else {
										if (h == toHour && m <= toMinute) {
											telephonyService.endCall();
										}
									}
								}
								if ((h >= fromHour && m >= fromMinute)
										&& (h <= toHour && m <= toMinute)) {
									telephonyService.endCall();
								}
							}
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
				}

			}
		};
		telMgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

		return START_STICKY;

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		// super.onDestroy();
		Log.e("stop service", "stop service");
		Toast.makeText(this, "Block call disable", Toast.LENGTH_SHORT).show();
		isRunning = false;
	}

	@Override
	@Deprecated
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		// super.onStart(intent, startId);
		Log.e("start service", "start service");
		// Toast.makeText(this, "MyService Started", Toast.LENGTH_LONG).show();
		isRunning = true;

	}

	public String getTelephonyOverview(TelephonyManager telMgr) {
		int callState = telMgr.getCallState();
		String callStateString = "NA";
		switch (callState) {
		case TelephonyManager.CALL_STATE_IDLE:
			callStateString = "IDLE";
			break;
		case TelephonyManager.CALL_STATE_OFFHOOK:
			callStateString = "OFFHOOK";
			break;
		case TelephonyManager.CALL_STATE_RINGING:
			callStateString = "RINGING";
			break;
		}
		return callStateString.toString();
	}

}
